package com.dacool.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dacool.app.sale.R;
import com.dacool.config.Config;
import com.dacool.helper.DaCoolHelper;
import com.dacool.http.BaseRequest;
import com.dacool.http.BaseRequest.ResponseHandler;
import com.dacool.http.GetProductListRequest;
import com.dacool.model.CartItem;
import com.dacool.model.DacoolProduct;
import com.dacool.model.ProductSource;
import com.dacool.util.ViewUtils;

public class ProductListFragment extends BaseFragment implements
		OnClickListener {

	private ArrayList<DacoolProduct> productList;
	private ArrayList<DacoolProduct> displayList;
	private ArrayAdapter<DacoolProduct> mAdapter;

	private Button defaultSortBtn;
	private Button sortByPriceBtn;
//	private Button sortByTimeBtn;
	private View tabIndicator1;
	private View tabIndicator2;
//	private View tabIndicator3;

	private int sortMode = 0;

	private ListView productListView;

	@Override
	protected int myLayoutID() {
		// TODO Auto-generated method stub
		return R.layout.frag_recommend;
	}

	@Override
	protected View myView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = super.onCreateView(inflater, container, savedInstanceState);
		defaultSortBtn = (Button) view.findViewById(R.id.sort_default);
		sortByPriceBtn = (Button) view.findViewById(R.id.sort_price);
//		sortByTimeBtn = (Button) view.findViewById(R.id.sort_time);
		productListView = (ListView) view.findViewById(R.id.productList);
		tabIndicator1 = view.findViewById(R.id.tabindicator1);
		tabIndicator2 = view.findViewById(R.id.tabindicator2);
//		tabIndicator3 = view.findViewById(R.id.tabindicator3);
		defaultSortBtn.setOnClickListener(this);
		sortByPriceBtn.setOnClickListener(this);
//		sortByTimeBtn.setOnClickListener(this);
		return view;
	}

	@Override
	protected boolean showDefaultSecondLeftButton() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		// productList = ProductSource.getRecommendProductList();
		productList = new ArrayList<DacoolProduct>();
		displayList = new ArrayList<DacoolProduct>(productList);
		mAdapter = new ArrayAdapter<DacoolProduct>(getActivity(), 0) {
			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return displayList.size();
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				DacoolProduct product = displayList.get(position);
				if (convertView == null) {
					View view = LayoutInflater.from(getActivity()).inflate(
							R.layout.productlistitem, null);
					ViewHolder holder = new ViewHolder();
					holder.imageView = (ImageView) view
							.findViewById(R.id.imageView);
					holder.titleView = (TextView) view
							.findViewById(R.id.titleLabel);
					holder.descriptionLabel = (TextView) view
							.findViewById(R.id.description);
					holder.priceLabel = (TextView) view
							.findViewById(R.id.priceLabel);
					holder.buybutton = (Button) view.findViewById(R.id.buyBtn);
					convertView = view;
					convertView.setTag(holder);
				}
				ViewHolder holder = (ViewHolder) convertView.getTag();
				holder.titleView.setText(product.getName());
				holder.descriptionLabel.setText(product.getDescription());
				holder.priceLabel.setText(String.format("¥ %.2f",
						product.getPrice()));
				ViewUtils.bmUtils.display(holder.imageView,
						product.getIconUrl());
				// holder.imageView.setimage(R.drawable.bannerimg);
				holder.buybutton.setOnClickListener(new BuyButtonListener(
						holder.imageView, product));
				return convertView;
			}

			class ViewHolder {
				ImageView imageView;
				TextView titleView;
				TextView descriptionLabel;
				TextView priceLabel;
				Button buybutton;
			}
		};
		productListView.setAdapter(mAdapter);
		productListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				DacoolProduct product = displayList.get(position);
				ProductInfoFragment fragment = new ProductInfoFragment();
				fragment.setProduct(product);
				getContainerActivity().addFragment(fragment);
			}
		});
	}

	@Override
	public String titleText() {
		// TODO Auto-generated method stub
		return "商品目录";
	}

	// @Override
	// protected boolean showDefaultLeftButton() {
	// return true;
	// }

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		this.loadProducts();
	}

	private void loadProducts() {
		this.showProgressDialog(null, false);
		new GetProductListRequest().setType(10)
				.setHandler(new ResponseHandler() {

					/**
					 * {“success”:true,data: { goodsId
					 * :”3342”, "name": "澳洲牛奶", " smallPic "
					 * :" http://app.dacool.com/dcmapp/media/1/2/1.jpg"
					 * , "bigPic"
					 * :" http://app.dacool.com/dcmapp/media/1/2/1.jpg"
					 * , "thumbnailPic"
					 * :" http://app.dacool.com/dcmapp/media/1/2/1.jpg"
					 * , " brief ": "商品描述",”price” :100}
					 */
					@Override
					public void handleResponse(BaseRequest request,
							int statusCode, String errorMsg, String response) {
						ProductListFragment.this.dismissProgressDialog();
						if (statusCode != 200)
							return;
						boolean success = false;
						try {
							JSONObject object = new JSONObject(response);
							success = object.optBoolean("success", false);

							JSONArray array = object.getJSONArray("data");
							productList = new ArrayList<DacoolProduct>();
							for (int i = 0; i < array.length(); i++) {
								JSONObject obj = array.getJSONObject(i);
								DacoolProduct product = new DacoolProduct();
								product.setName(obj.getString("name"));
								product.setDescription(obj.getString("brief"));
								// XXX price should be double already!!!
								product.setPrice(obj.getDouble("price"));
								product.setId(obj.getString("goodsId"));
								String url = obj.getString("smallPic");
								product.setIconUrl(url);
								JSONArray arr = obj.optJSONArray("bigPics");
								ArrayList<String> urls = new ArrayList<String>();
								if (arr != null)
									for (int j = 0; j < arr.length(); j++) {
										urls.add(arr.getString(j));
									}
								product.setImageUrls(urls);
								url = obj.getString("thumbnailPic");
								product.setThumbnailImageUrl(url);
								productList.add(product);
							}
							ViewUtils.runInMainThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									sort();
								}
							});
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();
	}

	private void sort() {
		displayList = new ArrayList<DacoolProduct>(productList);
		if (sortMode == 0) {

		} else if (sortMode == 1) {
			Collections.sort(displayList, new Comparator<DacoolProduct>() {
				@Override
				public int compare(DacoolProduct lhs, DacoolProduct rhs) {
					// TODO Auto-generated method stub

					return lhs.getPrice() > rhs.getPrice() ? 1
							: lhs.getPrice() < rhs.getPrice() ? -1 : 0;
				}
			});
		} else if (sortMode == 2) {
			Collections.sort(displayList, new Comparator<DacoolProduct>() {
				@Override
				public int compare(DacoolProduct lhs, DacoolProduct rhs) {
					if (lhs.getTime() != null && rhs.getTime() == null)
						return -1;
					if (lhs.getTime() == null && rhs.getTime() != null)
						return 1;
					if (lhs.getTime() == null && rhs.getTime() == null)
						return lhs.getName().compareTo(rhs.getName());
					if (lhs.getTime() != null && rhs.getTime() != null) {
						return rhs.getTime().compareTo(lhs.getTime());
					}
					return 0;
				}
			});
		}
		ViewUtils.runInMainThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mAdapter.notifyDataSetChanged();
			}
		});
	}

	@Override
	public void onClick(View v) {
		if (v == defaultSortBtn || v == sortByPriceBtn ) {
			if (v == defaultSortBtn) {
				sortMode = 0;

				defaultSortBtn.setClickable(false);
				sortByPriceBtn.setClickable(true);
//				sortByTimeBtn.setClickable(true);
				tabIndicator1.setBackgroundColor(0xFF85c400);
				tabIndicator2.setBackgroundColor(Color.TRANSPARENT);
//				tabIndicator3.setBackgroundColor(Color.TRANSPARENT);
			} else if (v == sortByPriceBtn) {
				sortMode = 1;

				defaultSortBtn.setClickable(true);
				sortByPriceBtn.setClickable(false);
//				sortByTimeBtn.setClickable(true);
				tabIndicator2.setBackgroundColor(0xFF85c400);
				tabIndicator1.setBackgroundColor(Color.TRANSPARENT);
//				tabIndicator3.setBackgroundColor(Color.TRANSPARENT);
			} 
//			else if (v == sortByTimeBtn) {
//				sortMode = 2;
//
//				defaultSortBtn.setClickable(true);
//				sortByPriceBtn.setClickable(true);
//				sortByTimeBtn.setClickable(false);
//				tabIndicator3.setBackgroundColor(0xFF85c400);
//				tabIndicator2.setBackgroundColor(Color.TRANSPARENT);
//				tabIndicator1.setBackgroundColor(Color.TRANSPARENT);
//			}
			sort();
		} else
			super.onClick(v);

	}

	class BuyButtonListener implements View.OnClickListener {

		private ImageView iv;
		private DacoolProduct product;
		ViewGroup animLayout;

		BuyButtonListener(ImageView view, DacoolProduct product) {
			iv = view;
			this.product = product;
		}

		@Override
		public void onClick(View v) {
			int[] start_location = new int[2];// 一个整型数组，用来存储按钮的在屏幕的X、Y坐标
			iv.getLocationInWindow(start_location);// 这是获取购买按钮的在屏幕的X、Y坐标（这也是动画开始的坐标）
			start_location[1] -= ViewUtils.rp(40);
			ImageView buyImg = new ImageView(getActivity());// buyImg是动画的图片，我的是一个小球（R.drawable.sign）
			buyImg.setImageDrawable(iv.getDrawable());// 设置buyImg的图片

			setAnim(buyImg, start_location, (int) (iv.getWidth() * .8),
					(int) (iv.getHeight() * .8));// 开始执行动画
		}

		/**
		 * @Description: 创建动画层
		 * @param
		 * @return void
		 * @throws
		 */
		private ViewGroup createAnimLayout() {
			ViewGroup rootView = (ViewGroup) getActivity().getWindow()
					.getDecorView();
			LinearLayout animLayout = new LinearLayout(getActivity());
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.MATCH_PARENT);
			animLayout.setLayoutParams(lp);
			animLayout.setId(Integer.MAX_VALUE);
			animLayout.setBackgroundResource(android.R.color.transparent);
			rootView.addView(animLayout);
			return animLayout;
		}

		private View addViewToAnimLayout(final ViewGroup vg, final View view,
				int[] location, int width, int height) {
			int x = location[0];
			int y = location[1];
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width,
					height);
			lp.leftMargin = x;
			lp.topMargin = y;
			view.setLayoutParams(lp);
			return view;
		}

		private void setAnim(final View v, int[] start_location, int width,
				int height) {
			animLayout = null;
			animLayout = createAnimLayout();
			animLayout.addView(v);// 把动画小球添加到动画层
			final View view = addViewToAnimLayout(animLayout, v,
					start_location, width, height);
			int[] end_location = new int[] {
					(int) (ProductListFragment.this.getActivity().getWindow()
							.getDecorView().getWidth() * .8),
					ProductListFragment.this.getActivity().getWindow()
							.getDecorView().getHeight() };// 这是用来存储动画结束位置的X、Y坐标
			// shopCart.getLocationInWindow(end_location);// shopCart是那个购物车

			// 计算位移
			int endX = end_location[0] - start_location[0];// 动画位移的X坐标
			int endY = end_location[1] - start_location[1];// 动画位移的y坐标
			TranslateAnimation translateAnimationX = new TranslateAnimation(0,
					endX, 0, 0);
			translateAnimationX.setInterpolator(new LinearInterpolator());
			translateAnimationX.setRepeatCount(0);// 动画重复执行的次数
			translateAnimationX.setFillAfter(true);

			TranslateAnimation translateAnimationY = new TranslateAnimation(0,
					0, 0, endY);
			translateAnimationY.setInterpolator(new AccelerateInterpolator());
			translateAnimationY.setRepeatCount(0);// 动画重复执行的次数
			translateAnimationX.setFillAfter(true);

			AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0.4f);
			alphaAnimation.setFillAfter(true);

			ScaleAnimation scaleAnimation = new ScaleAnimation(1, 0.6f, 1, 0.6f);
			scaleAnimation.setFillAfter(true);

			AnimationSet set = new AnimationSet(false);
			set.setFillAfter(false);
			set.addAnimation(translateAnimationY);
			set.addAnimation(translateAnimationX);
			set.addAnimation(alphaAnimation);
			set.addAnimation(scaleAnimation);
			set.setDuration(400);// 动画的执行时间
			view.startAnimation(set);
			// 动画监听事件
			set.setAnimationListener(new AnimationListener() {
				// 动画的开始
				@Override
				public void onAnimationStart(Animation animation) {
					v.setVisibility(View.VISIBLE);

				}

				@Override
				public void onAnimationRepeat(Animation animation) {
					// TODO Auto-generated method stub
				}

				// 动画的结束
				@Override
				public void onAnimationEnd(Animation animation) {
					v.setVisibility(View.GONE);
					CartItem item = new CartItem();
					item.setProduct(product);
					DaCoolHelper.sharedInstance().addItem(item, 1);
					// buyNum++;//让购买数量加1
					// buyNumView.setText(buyNum + "");//
					// buyNumView.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
					// buyNumView.show();
				}
			});

		}
	}

}
